package com.wangyadong.hobby.javanetwork.socket;

import com.wangyadong.hobby.common.utils.DateUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2019/7/1210:18
 **/
public class SocketTest {

    public static void main(String[] args) {

    }

    public static void simpleSocketTest() {

        try {
            try (ServerSocket socket = new ServerSocket(22)) {
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void simpleClient() {
        Socket socket = null;
        try {
            StringBuilder builder = new StringBuilder();
            socket = new Socket("localhost", 22);
            socket.setSoTimeout(15000);
            InputStream inputStream = socket.getInputStream();
            for (int i = inputStream.read(); i != -1; i = inputStream.read()) {
                builder.append(i);
            }
            System.out.println(builder);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Date getDateFronmNetWork() throws ParseException {
        StringBuilder builder = new StringBuilder();
        try {
            try (Socket socket = new Socket("localhost", 22)) {
                socket.setSoTimeout(15000);
                InputStream inputStream = socket.getInputStream();
                for (int i = inputStream.read(); i != -1; i = inputStream.read()) {
                    builder.append(i);
                }
//                socket.set
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return parseDate(builder.toString());
    }

    static Date parseDate(String s) throws ParseException {
        String[] pieces = s.split(" ");
        String dataTime = pieces[1] + pieces[2] + " UTC";
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.DATETIME_FORMAT_WITH_POINT_Z);
        return dateFormat.parse(dataTime);


    }
}
